package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdGenerator;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {


    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private RedisIdGenerator redisIdGenerator;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient;

    private IVoucherOrderService proxy;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    //阻塞队列
    private BlockingQueue<VoucherOrder> voucherOrderQueue = new ArrayBlockingQueue<>(1024 * 1024);

    private static final ExecutorService SECKILL_ORDER_HANDLER = Executors.newSingleThreadExecutor();


    @PostConstruct
    private void init() {
        SECKILL_ORDER_HANDLER.submit(new VoucherOrderHandler());
    }


    private class VoucherOrderHandler implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    VoucherOrder order = voucherOrderQueue.take();
                    handlerVoucherOrder(order);

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        }
    }


    private class VoucherOrderHandlerWithMQ implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create("stream.orders", ReadOffset.lastConsumed())
                    );
                    if(list==null||list.isEmpty()){
                        continue;
                    }

                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    proxy.creatOrder(voucherOrder);


                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

            }
        }
    }

    public void handlerVoucherOrder(VoucherOrder order) {

        //获取用户
        Long userId = order.getUserId();

//        SimpleRedisLock redisLock = new SimpleRedisLock("orderSeckill:"+userId,stringRedisTemplate);

        RLock redisLock = redissonClient.getLock("orderSeckill:" + userId);

        boolean success = redisLock.tryLock();

        if (!success){
            log.error("重复下单");
            return;
        }
        try {
            proxy.creatOrder(order);
        } finally {
            redisLock.unlock();
        }


    }




    @Override
//    public Result seckillVoucher(Long voucherId) {
//
//        //先查询优惠券的相关信息
//        SeckillVoucher skVoucher = seckillVoucherService.getById(voucherId);
//
//        LocalDateTime now = LocalDateTime.now();
//        if (now.isBefore(skVoucher.getBeginTime()) || now.isAfter(skVoucher.getEndTime())) {
//            return Result.fail("活动尚未开始或已结束");
//        }
//        Integer stock = skVoucher.getStock();
//        if (stock < 1) {
//            return Result.fail("优惠卷已被抢光");
//        }
//
//
//        //创建订单
//        Long userId = UserHolder.getUser().getId();
//
//
////        SimpleRedisLock redisLock = new SimpleRedisLock("orderSeckill:"+userId,stringRedisTemplate);
//
//        RLock redisLock = redissonClient.getLock("orderSeckill:"+userId);
//
//        boolean success = redisLock.tryLock();
//
//        if(!success)
//            return Result.fail("请求出错");
//
//        try {
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.creatOrder(voucherId);
//        } finally {
//            redisLock.unlock();
//        }
//
//
//    }

    @Transactional

    /**
     * 购买资格判定
     */
    public Result seckillVoucher(Long voucherId) {

        Long userId = UserHolder.getUser().getId();
        long orderId = redisIdGenerator.nextId("order");

        Long res = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(), String.valueOf(orderId)
        );

        int r = res.intValue();
        if (r != 0) {
            return Result.fail(r == 1 ? "lua库存不足" : "lua不能重复下单");
        }

        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(UserHolder.getUser().getId());
        voucherOrder.setVoucherId(voucherId);
        //阻塞队列方式
        voucherOrderQueue.add(voucherOrder);
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        //rabbitMQ方式
        //rabbitTemplate.convertAndSend("seckill.direct","seckill.order",voucherOrder)


        return Result.ok(orderId);

    }

    @Transactional
    public void creatOrder(VoucherOrder voucherOrder) {


        /// 重要————扣减库存——————要操作数据库
        seckillVoucherService.update()
                .setSql("stock=stock-1")
                .eq("voucher_id", voucherOrder.getVoucherId()).gt("stock", 0)
                .update();

//        VoucherOrder voucherOrder = new VoucherOrder();
//
//        long id = redisIdGenerator.nextId("order");
//        voucherOrder.setId(id);
//        voucherOrder.setUserId(UserHolder.getUser().getId());
//        voucherOrder.setVoucherId(voucherId);
        save(voucherOrder);


//        return Result.ok(id);
    }






}
